package com.cjq.controller;

import com.cjq.domain.StatNumVaryDTO;
import com.cjq.domain.StatRatioDTO;
import com.cjq.service.QuestionnaireService;
import com.cjq.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author junqiancai@foxmail.com
 * @since 2021/6/20 19:30
 */
@RestController
public class StatController {
    @Autowired
    private QuestionnaireService questionnaireService;

    @PreAuthorize("hasAnyRole('ADMIN','SUPER')")
    @GetMapping("/stat/ratio")
    public Result getRatioStat(@RequestParam(value = "date",required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) Date date){
        if(date==null)date = new Date();
        java.sql.Date targetDate = new java.sql.Date(date.getTime());
        List<StatRatioDTO> statRatioDTOS = questionnaireService.selectStatRatio(targetDate);
        statRatioDTOS.forEach(dto->{
            if(dto.getClockNum()==null)dto.setClockNum(0);
            dto.setRatio(dto.getClockNum()/(double)dto.getAllNum());
        });
        return Result.succeed(Result.SUCCESS,"查询成功",statRatioDTOS);
    }

    @PreAuthorize("hasAnyRole('ADMIN','SUPER')")
    @GetMapping("/stat/numVary")
    public Result getNumVaryStat(){
        final List<StatNumVaryDTO> statNumVaryDTOS = questionnaireService.selectStatNumVary();
        final Calendar calendar = Calendar.getInstance();
        final HashSet<String> dateSet = new HashSet<>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        statNumVaryDTOS.forEach(it->dateSet.add(sdf.format(it.getClockInDate())));
        for(int i=0;i<14;i++){
            final Date date = calendar.getTime();
            if(!dateSet.contains(sdf.format(date))){
                statNumVaryDTOS.add(new StatNumVaryDTO().setRiskNum(0).setExceptionNum(0).setClockInDate(date));
            }
            calendar.add(Calendar.DAY_OF_YEAR,-1);
        }
        statNumVaryDTOS.sort(Comparator.comparing(StatNumVaryDTO::getClockInDate));
        return Result.succeed(Result.SUCCESS,"查询成功",statNumVaryDTOS);
    }
}
